package com.label.Utils;

import com.label.Config.Common.Constant;
import com.label.Model.Do.User;
import com.label.Model.Query.UserQuery;
import com.label.Service.UserService;
import com.label.Utils.Common.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 获取当前登录用户工具类
 */
@Component
public class UserUtil {

    public static UserService userService;

    @Resource
    public void setService(UserService userService){
        UserUtil.userService=userService;
    }

    /**
     * 获取当前登录用户
     */
    public static User getUser() {
        try {
            String token = SecurityUtils.getSubject().getPrincipal().toString();
            String account = JwtUtil.getClaim(token, Constant.ACCOUNT);
            return userService.getOneUserByAccount(new UserQuery(account));
        }catch (Exception e){
            return new User();
        }
    }

    /**
     * 获取当前登录用户Id
     * @return
     */
    public static Long getUserId() {
        return getUser().getId();
    }

    /**
     * 获取当前登录用户Account
     */
    public String getAccount() {
        String token = SecurityUtils.getSubject().getPrincipal().toString();
        // 解密获得Account
        return JwtUtil.getClaim(token, Constant.ACCOUNT);
    }
}
